package com.hcyy.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	//private static final String[] IGNORE_URI = {"image", "login","index","js","css"};
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		boolean flag = true;
		/*String url = request.getRequestURL().toString();
		System.out.println(">>>: " + url);
		for (String s : IGNORE_URI) {
			if (url.contains(s)) {
				flag = true;
				break;
			}
		}*/
		String uri = request.getServletPath();
		if(uri.equals("/Shop/Detail")||uri.equals("/Shop/QuickOrder")){
			uri=null;
		}
		/*if(request.getParameter("productid")!=null){
			String params=request.getParameter("productid");
			uri = uri+"?productid="+params;
		}*/
		if(request.getParameter("idarray")!=null){
			String params=request.getParameter("idarray");
			uri = uri+"?idarray="+params;
		}
		if(request.getParameter("orderstatus")!=null){
			String params=request.getParameter("orderstatus");
			uri = uri+"?orderstatus="+params;
		}
		if(request.getParameter("sid")!=null){
			String params=request.getParameter("sid");
			uri = uri+"?sid="+params;
		}
		/**
		 * 登录中存储的sjid，
		 * 用户请求的reqSjid（地址栏参数）
		 */
		Integer sjid=(Integer) request.getSession().getAttribute("sjid");//从session中获取登录存储的sjid
		Integer reqSjid=1;
		if(request.getParameter("sjid")!=null){//请求的sjid不为null
			reqSjid=Integer.parseInt(request.getParameter("sjid"));
			/*if(uri!=null){
				if(uri.indexOf("?")<=0){
					uri = uri+"?sjid="+reqSjid;
				}else{
					uri = uri+"&&sjid="+reqSjid;
				}
			}*/
		}
		if(request.getSession().getAttribute("user")!=null&&reqSjid.equals(sjid)){
			flag=true;
		}else{
//			request.getRequestDispatcher("/login").forward(request, response);
			response.sendRedirect(request.getContextPath()+"/login?sjid="+reqSjid);
			request.getSession().setAttribute("uri", uri);
			flag=false;
		}
		return flag;
	}
	
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		super.afterCompletion(request, response, handler, ex);
	}

}
